package com.cn.common.implement;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import cn.com.allunion.common.net.HttpClientUtil;
import com.alibaba.druid.support.logging.Log;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.cn.json.JSONHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TeleCheckImp {
	private static final Logger LOGGER = LoggerFactory.getLogger(TeleCheckImp.class) ;

	/**
	 * 取得手机号码所属地
	 * 
	 * @param mobile
	 * @return 手机号码所属地
	 * @throws Exception
	 */
	public static String getMobileAddress(String mobile) throws Exception {
		String address = "";
		try {
			mobile = mobile.trim();
			if (mobile.matches("^(13|15|18)\\d{9}$")
					|| mobile.matches("^(013|015|018)\\d{9}$")) // 以13，15，18开头，后面九位全为数字
			{
				String url = "http://www.ip138.com:8080/search.asp?action=mobile&mobile="
						+ mobile;
				URLConnection connection = (URLConnection) new URL(url)
						.openConnection();
				connection.setDoOutput(true);
				InputStream os = connection.getInputStream();
				Thread.sleep(100);
				int length = os.available();
				byte[] buff = new byte[length];
				os.read(buff);
				String s = new String(buff, "gbk");
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("result==" + s);
                }
				int len = s.indexOf("卡号归属地");
				s = s.substring(len, len + 100);
				len = s.lastIndexOf("</TD>");
				address = s.substring(0, len);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("result==" + address);
                }
				len = address.lastIndexOf(">");
				address = address.substring(len + 1, address.length());
				address = address.replace("&nbsp;", ",");
				address = address.replace("d> -->", "");
				address = address.replace(" -->", "");
				address = address.replace("-->", "");
				s = null;
				buff = null;
				os.close();
				connection = null;
			}
		} catch (Exception e) {
			address = "未知";
			LOGGER.error("手机所属地查询失败=======", e);
		}
		return address;
	}

	/**
	 * 淘宝网 API地址：
	 * http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=15850781443 参数：
	 * 
	 * tel：手机号码 返回：JSON 拍拍 API地址：
	 * http://virtual.paipai.com/extinfo/GetMobileProductInfo
	 * ?mobile=15850781443&amount=10000&callname=getPhoneNumInfoExtCallback 参数：
	 * 
	 * mobile：手机号码 callname：回调函数 amount：未知（必须） 返回：JSON 财付通 API地址：
	 * http://life.tenpay
	 * .com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile=15850781443 参数：
	 * 
	 * chgmobile：手机号码 返回：xml 百付宝 API地址：
	 * https://www.baifubao.com/callback?cmd=1059
	 * &callback=phone&phone=15850781443 参数：
	 * 
	 * phone：手机号码 callback：回调函数 cmd：未知（必须） 返回：JSON 115 API地址：
	 * http://cz.115.com/?
	 * ct=index&ac=get_mobile_local&callback=jsonp1333962541001
	 * &mobile=15850781443 参数：
	 * 
	 * mobile：手机号码 callback：回调函数 返回：JSON 有道 API地址：
	 * http://www.youdao.com/smartresult
	 * -xml/search.s?jsFlag=true&type=mobile&q=13985046628 参数：
	 * 
	 * type：mobile(表示查询手机号码) q：手机号码 返回：JSON
	 * 
	 * 
	 * /** 财付通手机归属地查询
	 * 
	 * @throws IOException
	 * @throws MalformedURLException
	 * @throws InterruptedException
	 */
	public static String tenpay(String tel) throws MalformedURLException,
			IOException, InterruptedException {
		String result = null;
		String url = "http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile="
				+ tel;
		URLConnection con = (URLConnection) new URL(url).openConnection();
		con.setDoOutput(true);
		InputStream os = con.getInputStream();
		Thread.sleep(100);
		int length = os.available();
		byte[] buff = new byte[length];
		os.read(buff);
		String s = new String(buff, "gbk");
		result = s;
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug(s);
        }
		return result;
	}

	/**
	 * 拍拍网手机归属地查询
	 * 
	 * @throws IOException
	 * @throws MalformedURLException
	 * @throws InterruptedException
	 * @throws JSONException
	 * @param tel
	 *            电话号码
	 * @return 归属地
	 */
	// 拍拍网
	public static String paipai(String tel) throws MalformedURLException,
			IOException, InterruptedException, JSONException {
		String result = null;
		String url = "http://virtual.paipai.com/extinfo/GetMobileProductInfo?mobile="
				+ tel + "&amount=10000&callname=getPhoneNumInfoExtCallback";
		URLConnection con = (URLConnection) new URL(url).openConnection();
		con.setDoOutput(true);
		InputStream os = con.getInputStream();
		Thread.sleep(100);
		int length = os.available();
		byte[] buff = new byte[length];
		os.read(buff);
		String s = new String(buff, "gbk");
		s = s.substring(s.lastIndexOf("(") + 1, s.indexOf(")"));
		result = s;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(s);
        }
		JSONHelper jh = new JSONHelper();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(jh.getJSONString(jh.getJSONObject(s), "province"));
        }
		return result;
	}

	/**
	 * 手机归属地查询
	 * 
	 * @param tel
	 *            电话号码
	 * @return 归属地
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws JSONException
	 */
	public static String taobao(String tel) {
		String result = null;
		// http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13031039465
		String url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + tel;
		try {
            String s = HttpClientUtil.doGet(url) ;
//			String s = new String(buff, "gbk");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(s);
            }
			s = s.substring(s.indexOf("=") + 1);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(s);
            }
			result = s;
			JSONHelper jh = new JSONHelper();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(jh.getJSONString(jh.getJSONObject(s), "province"));
            }
		} catch (JSONException e) {
            LOGGER.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 百付宝属地查询
	 * 
	 * @param url
	 *            指定API的URL字符串
	 * @return JSON字符串
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws JSONException
	 * @return 归属地
	 */
	public static String baifubao(String url) throws MalformedURLException,
			IOException, InterruptedException, JSONException {
		URLConnection connection = (URLConnection) new URL(url)
				.openConnection();
		connection.setDoOutput(true);
		InputStream os = connection.getInputStream();
		Thread.sleep(100);
		int length = os.available();
		byte[] buff = new byte[length];
		os.read(buff);
		String s = new String(buff, "gbk");
		s = s.substring(s.indexOf("(") + 1);
		JSONHelper jh = new JSONHelper();
		JSONObject jo = jh.getJSONObject(s);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(jo.toString());
            LOGGER.debug(jh.getJSONString(jo, "meta").subSequence(0,
                    jh.getJSONString(jo, "meta").length() - 1)
                    + jh.getJSONString(jo, "data").substring(1));
        }
		String result = s;
		return result;
	}

	public static void main(String[] args) throws Exception {
		// System.out.println(TeleCheckImp.getMobileAddress("13031039465"));
		// System.out.println(TeleCheckImp.taobao("13031039465"));
		// System.out.println(TeleCheckImp.paipai("13031039465"));
		// System.out.println(TeleCheckImp.tenpay("13031039465"));
		TeleCheckImp.baifubao("https://www.baifubao.com/callback?cmd=1059&callback=phone&phone=15850781443");

	}
}
